import 'dart:convert';

import 'package:crypto/crypto.dart';
import 'package:dio/dio.dart';

class SignInterceptor extends Interceptor {
  static const signKey = "signkey";
  static const signValue = "4b87298487e0091ee6bf2e3baa0de2e3";

  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    if (options.method == "GET") {
      _dynamicParams(options.queryParameters);
    } else if (options.method == "POST") {
      _dynamicParams(options.queryParameters);
    }
    super.onRequest(options, handler);
  }

  void _dynamicParams(Map<String, dynamic> queryParameters) {
    // 是否添加时间戳
    queryParameters["time"] = DateTime.now().microsecondsSinceEpoch ~/ 1000;
    queryParameters["timezone"] = "8";
    // 是否签名
    queryParameters["sign"] = _sign(queryParameters);
  }

  String _sign(Map<String, dynamic> queryParameters) {
    var sortedKeys = queryParameters.keys.toList()..sort();
    var stringBuilder = "";
    for (var element in sortedKeys) {
      stringBuilder += "$element=${queryParameters[element]}&";
    }
    stringBuilder += "$signKey=$signValue";
    var content = const Utf8Encoder().convert(stringBuilder);
    return md5.convert(content).toString();
  }
}
